package com.fr.lintcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Q1683 {

    /**
     * @param n: 
     * @param v: 
     * @return: nothing
     */
    public int killMonster(int n, int[][] v) {
        // 
    	if(v == null || v.length < 1 || v[0].length != 5) {
    		return 0;
    	}
    	Node a = new Node(v[0]);
    	List<Node> list = new ArrayList<>();
    	for(int i = 1; i < v.length; i ++) {
    		list.add(new Node(v[i]));
    	}
    	int count = 0;
    	Collections.sort(list);
    	while(true) {
    		if(list.isEmpty()) {
    			break;
    		}
    		Node tmp = null;
    		for(Node node : list) {
    			if(a.a >= node.a && a.b >= node.b && a.c >= node.c && a.d >= node.d && a.e >= node.e) {
    				tmp = node;
    				break;
    			}
    		}
    		if(tmp != null) {
    			list.remove(tmp);
    			a.a += tmp.a;
    			a.b += tmp.b;
    			a.c += tmp.c;
    			a.d += tmp.d;
    			a.e += tmp.e;
    			count ++;
    		}else {
    			break;
    		}
    		
    	}
    	return count;
    }

    
    class Node implements Comparable<Node>{
    	public Node(int [] t) {
    		this.a = t[0];
    		this.b = t[1];
    		this.c = t[2];
    		this.d = t[3];
    		this.e = t[4];
    	}
    	public int a;
    	public int b;
    	public int c;
    	public int d;
    	public int e;
		@Override
		public int compareTo(Node o) {
			if(this.a == o.a) {
				if(this.b == o.b) {
					if(this.c == o.c) {
						if(this.d == o.d) {
							if(this.e == o.e) {
								 return 0;
							}else {
								return e - o.e;
							}
						}else {
							return d - o.d;
						}
					}else {
						return c - o.c;
					} 
				}else {
					return b - o.b;
				}
			}else {
				return a - o.a;
			}
		}
    	
    }
}
